//
//  MainViewController.m
//  HDYS
//
//  Created by qianfeng on 15-4-21.
//  Copyright (c) 2015年 kay. All rights reserved.
//

#import "MainViewController.h"
#import "MainTableViewCell.h"
#import "GoodsInfoViewController.h"
#import "MainTabBarViewController.h"
#import "SettingsViewController.h"
#import "Header.h"

#import "ProgressHUD.h"
#import "AppDelegate.h"

#import "DBManager.h"

@interface MyButton : UIButton

@end
@implementation MyButton

-(void)setHighlighted:(BOOL)highlighted {}

@end


@interface MainViewController () <UITableViewDataSource, UITableViewDelegate, MainTableViewCellDelegate, UIScrollViewDelegate>
{
    BOOL isFav;
    AppDelegate *app;
}

@property (nonatomic, strong) UIScrollView *sv;

@property (nonatomic, strong) UITableView *mainTableView;

//最新
@property (nonatomic, strong) NSMutableArray *latestDataArr;
//推荐
@property (nonatomic, strong) NSMutableArray *favDataArr;


@property (nonatomic, strong) UIView *tempView;


@end

@implementation MainViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    [self createNavItems];
    self.latestDataArr = [NSMutableArray arrayWithCapacity:0];
    self.favDataArr = [NSMutableArray arrayWithCapacity:0];
    
    
    [self loadData];
    [self createTableView];
//    [self createTimer];
}

//- (void)createProgressHUD {
//    UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49)];
//    tempView.backgroundColor = [UIColor grayColor];
//    [self.view addSubview:tempView];
//    self.tempView = tempView;
//    
//    [ProgressHUD showOnView:tempView];
//}

/**
 请求数据 完成后创建滚动视图
 */
-(void)loadData{
    app = (id)[UIApplication sharedApplication].delegate;
    app.sessionManger = [AFHTTPSessionManager manager];
    app.sessionManger.responseSerializer = [AFHTTPResponseSerializer serializer];
    [app.sessionManger GET:INDEX_URL parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        id json = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if ([json isKindOfClass:[NSDictionary class]]) {
            NSDictionary *d = [NSDictionary dictionaryWithDictionary:json];
            //推荐
            NSArray *favDataArr = [d objectForKey:@"tdata"];
            for (NSDictionary *dic in favDataArr) {
                MainDataModel *model = [[MainDataModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.favDataArr addObject:model];
            }
            //最新
            NSArray *latestDataArr = [d objectForKey:@"zdata"];
            for (NSDictionary *dic in latestDataArr) {
                MainDataModel *model = [[MainDataModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                [self.latestDataArr addObject:model];
            }
        }
        [self.mainTableView reloadData];
//        [ProgressHUD hideOnView:self.tempView];
//        [self.tempView removeFromSuperview];
//        self.tempView = nil;

    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@",error);
//        [ProgressHUD hideOnView:self.tempView];
//        [self.tempView removeFromSuperview];
//        self.tempView = nil;
    }];
    
}

#pragma mark - 创建子控件
-(void)createNavItems{
    self.navigationController.navigationBar.translucent = NO;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(0, 0, 50, 35);
    [btn setBackgroundImage:[UIImage imageNamed:@"page_red_sort@3x"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(leftBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithCustomView:btn];
    self.navigationItem.leftBarButtonItem = item;
}


-(void)createTableView{
    UITableView *mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49) style:UITableViewStyleGrouped];
    mainTableView.delegate = self;
    mainTableView.dataSource = self;
    
    mainTableView.sectionFooterHeight = 10;
    mainTableView.sectionHeaderHeight = 10;
    mainTableView.tableHeaderView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 300);
    [self.view addSubview:mainTableView];
    self.mainTableView = mainTableView;
    
//    [self createProgressHUD];
    
    //表头视图
    UIScrollView *sv = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    sv.contentSize = CGSizeMake(SCREEN_WIDTH * 6, 200);
    sv.contentOffset = CGPointMake(SCREEN_WIDTH, 0);
    sv.pagingEnabled = YES;
    sv.tag = 44;
    sv.delegate = self;
    self.sv = sv;
    
    NSArray *array = @[@"image3",@"image0",@"image1",@"image2",@"image3",@"image0"];
    for (int i = 0; i < array.count; i++) {
        MyButton *imgBtn= [MyButton buttonWithType:UIButtonTypeCustom];
        imgBtn.tag = 34 + i;
        imgBtn.frame = CGRectMake(i * SCREEN_WIDTH, 0, SCREEN_WIDTH, 200);
        [imgBtn setBackgroundImage:[UIImage imageNamed:array[i]] forState:UIControlStateNormal];
        [imgBtn addTarget:self action:@selector(imgBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [sv addSubview:imgBtn];
    }
    mainTableView.tableHeaderView = sv;
    
    UISwipeGestureRecognizer *rightSwipe = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(swipeRight:)];
    rightSwipe.direction = UISwipeGestureRecognizerDirectionRight;
    [mainTableView addGestureRecognizer:rightSwipe];
}

-(void)swipeRight:(UISwipeGestureRecognizer *)ges{
    if ([self.delegate respondsToSelector:@selector(mainViewControllerdidSwipeRight)]) {
        [self.delegate mainViewControllerdidSwipeRight];
    }
}

-(void)createTimer{
    [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(updateTimer) userInfo:nil repeats:YES];
}

-(void)updateTimer{
    CGPoint offset = self.sv.contentOffset;
    offset.x += SCREEN_WIDTH;
    [self.sv setContentOffset:offset animated:YES];
    if (self.sv.contentOffset.x == 4 * SCREEN_WIDTH) {
        [self.sv setContentOffset:CGPointZero];
    }
}

#pragma mark - TableView协议方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (isFav) {
        return self.favDataArr.count;
    } else {
        return self.latestDataArr.count;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        static NSString *cellIdentifier = @"firstCellId";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[@"推荐",@"最新"]];
            seg.frame = CGRectMake((SCREEN_WIDTH - 200) / 2, 5, 200, 30);
            seg.selectedSegmentIndex = 0;
            [seg addTarget:self action:@selector(segValueDidChanged:) forControlEvents:UIControlEventValueChanged];
            [cell.contentView addSubview:seg];
        }
        return cell;
    } else {
        static NSString *cellIdentifier = @"mainCellId";
        MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        if (cell == nil) {
            cell = [[MainTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        MainDataModel *model;
        if (isFav) {
            model = self.favDataArr[indexPath.section];
        } else {
            model = self.latestDataArr[indexPath.section];
        }
        [cell configureUIWithModel:model];
        for (MainDataModel *m in [[DBManager sharedManager] allData]) {
            if ([m.gId isEqualToString:model.gId]) {
                [cell.likeBtn setTitle:@"取消收藏" forState:UIControlStateNormal];
            }
        }
        
        return cell;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return 40.0f;
    }
    return 440.0f;
}

#pragma mark - MainTableViewCellDelegate协议方法
-(void)mainTableViewCellWillGoToGoodsInfoWithModel:(MainDataModel *)goodsModel{
    GoodsInfoViewController *goodsVC = [[GoodsInfoViewController alloc] init];
    goodsVC.hidesBottomBarWhenPushed = YES;
    goodsVC.model = goodsModel;
    [self presentViewController:goodsVC animated:YES completion:nil];
}

-(void)mainTableViewCellWillCollectGoodsWithModel:(MainDataModel *)goodsModel andIsCollect:(BOOL)isCollect{
    DBManager *manager = [DBManager sharedManager];
    if (isCollect) {
        [manager insertDataWithModel:goodsModel];
    } else {
        [manager deleteDataWithModel:goodsModel];
    }
    NSLog(@"%@",[manager allData]);
}


#pragma mark - SegmentedControl
- (void)segValueDidChanged:(UISegmentedControl *)seg{
    if (seg.selectedSegmentIndex == 0) {
        isFav = YES;
    } else {
        isFav = NO;
    }
    [self.mainTableView reloadData];
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.mainTableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

#pragma mark - 表头滚动视图
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if (scrollView.tag == 44) {
        if (scrollView.contentOffset.x == 0) {
            [scrollView setContentOffset:CGPointMake(SCREEN_WIDTH * 4, 0)];
        } else if (scrollView.contentOffset.x == SCREEN_WIDTH * 5) {
            [scrollView setContentOffset:CGPointMake(SCREEN_WIDTH, 0)];
        }
    }
}

//进入广告页
- (void)imgBtnClick:(MyButton *)btn {
    
}

#if 0
-(void)toShouCang:(NSString *)jid{
    NSDictionary *dic=@{
                        @"id":jid
                        };
    
    [app.sessionManger GET:TO_SHOUCANG parameters:dic success:^(NSURLSessionDataTask *task, id responseObject) {
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}
#endif

-(void)leftBtnClick{
    if ([self.delegate respondsToSelector:@selector(mainViewControllerdidSwipeRight)]) {
        [self.delegate mainViewControllerdidSwipeRight];
    }
}


@end
